<template>
  <div>
    <!-- 顶部下拉刷新组件 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <!-- 底部加载列表组件 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="50"
      >
        <!-- list组件初始化时会先判断一次是否触底，可以通过immediate-check关闭 -->
        <ArticleItem
          v-for="obj in list"
          :key="obj.art_id"
          :articleObj="obj"
          @dislikeEV="dislikeFn"
          @reportEV="reportFn"
          @click.native="itemClickFn(obj.art_id)"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getAllArticlesAPI, dislikeArticleAPI, reportArticleAPI } from "@/api";
import ArticleItem from "@/components/ArticleItem";
import { MyNotify } from "@/utils/Notify";

export default {
  props: {
    channelId: Number, //频道id
  },
  data() {
    return {
      list: [], //存放频道所有文章
      loading: false, //底部是否正在加载
      finished: false, //数据是否全部加载完毕
      theTime: new Date().getTime(), //方便进行分页
      isLoading: false, //下拉刷新是否正在加载
    };
  },
  components: {
    ArticleItem,
  },
  async created() {
    //创建时获取频道文章数据
    this.getAllArticlesFn();
  },
  methods: {
    //网络请求优化函数
    async getAllArticlesFn() {
      //获取加载数据
      const res = await getAllArticlesAPI({
        channel_id: this.channelId,
        timestamp: this.theTime,
      });

      //将获取文章数据加入文章列表
      this.list = [...this.list, ...res.data.data.results];
      //保存上一次推荐文章的时间戳
      this.theTime = res.data.data.pre_timestamp;

      //底部加载完成
      this.loading = false;

      //判断文章数据是否已经全部拿完
      if (res.data.data.pre_timestamp === null) {
        this.finished = true;
      }

      //下拉刷新完成
      this.isLoading = false;
    },

    //组件滚到底部时触发，并将loading设置为true
    onLoad() {
      //防止第一次初始化时与created获取数据重复
      if (this.list.length === 0) {
        this.loading = false;
        return;
      }
      this.getAllArticlesFn();
    },

    //下拉刷新时调用
    async onRefresh() {
      //清空list中的内容，重置theTime
      this.list = [];
      this.theTime = new Date().getTime();

      this.getAllArticlesFn();
    },

    //反馈-不感兴趣
    async dislikeFn(id) {
      // 捕获同步异常
      try {
        await dislikeArticleAPI(id);
        MyNotify({ type: "success", message: "感谢您的反馈" });
      } catch (error) {}
    },
    //反馈-举报内容
    async reportFn(id, value) {
      try {
        await reportArticleAPI({ artId: id, type: value });
        MyNotify({ type: "success", message: "举报成功" });
      } catch (error) {}
    },
    //单个文章点击事件
    itemClickFn(id) {
      this.$router.push({ path: `/detail?art_id=${id}` });
    },
  },
};
</script>

<style></style>
s
